<?php
class WikiController extends Zend_Controller_Action {

	public function init() {

	}

	public function indexAction() {
		$page = $this->getRequest()->getParam('page', null);
		$this->view->page = $page;
				
		$path = realpath(APPLICATION_PATH . "/../data/" . $page);
		if (file_exists($path)) {
			
			$parser = new Wiki_CreoleParser();
			
			$this->view->headTitle()->prepend(ucfirst($page));
			$content = file_get_contents($path);
			$output = $parser->parse($content);
		
		} else {
			throw new Zend_Controller_Dispatcher_Exception('Could not find page ' . $page);
		}
			
		$this->view->output = $output;
	}
	
	public function editAction() {
		Zend_Controller_Front::getInstance()
			->getPlugin('Wiki_Controller_Plugin_Cache')
			->setCaching(false);
		
		$page = $this->getRequest()->getParam('page', null);
		$this->view->page = $page;
		 
		$path = realpath(APPLICATION_PATH . "/../data/" . $page);
		
		$form = $this->getForm($page);
				
		if (!$this->getRequest()->isPost()) {
			
			if (file_exists($path)) {
				
				$this->view->headTitle()->prepend('Edit page ' . ucfirst($page));
				$content = file_get_contents($path);
				$form->getElement('content')->setValue($content); 
			
			} else {
				
				$this->view->headTitle()->prepend('Create page ' . ucfirst($page));
			}
			
			$this->view->form = $form;
			return;
		
		} else {
			
			if (!$form->isValid($_POST)) {
				$this->view->form = $form;
				return;
			}
			
			$values = $form->getValues();
			
			if ($values['content'] != null) {
				file_put_contents($path, $values['content']);
				// TODO commit file
			}
			
			$this->_helper->_redirector->goToRoute(
				array(
					'page' => $page
				),
				'wiki'
			);
		}
	}
	
	private function getForm($page) {
		$form = new Zend_Form();
		$form->setAction('/edit/' . $page)
			->setMethod('post');
		
		$textarea = new Zend_Form_Element_Textarea('content');
		$textarea->setRequired(true)
			->setLabel('Content');
		
		$submit = new Zend_Form_Element_Submit('submit');
		$submit->setLabel('Edit');
		
		$form->addElement($textarea)
			->addElement($submit);
		
		return $form;
	}
}